import React, { PureComponent, Fragment } from 'react';
import { Card, Radio, Button } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import _ from 'lodash';
import ProjectsPath from '@/components/ProjectsPath';
import qs from 'qs';
import router from 'umi/router';
import CurrentStage from '../components/CurrentStage';
import PageEmpty from '@/components/PageEmpty';
import PageTop from './components/PageTop';
import styles from '../../index.less';
import AuthorizedButton from '@/components/AuthorizedButton';
import { BaseTable, utils } from '@/components/BaseTable';
import { getTitleTree, getFixedColumns } from '../utils/tableUtils';

@connect(state => ({
  items: state.SupplyPlanDetailItems,
  overAllYears: state.SupplyPlanDetailItemsYears.overAllYears,
  currentYear: state.SupplyPlanDetailItemsYears.currentYear,
  currentMonths: state.SupplyPlanDetailItemsYears.currentMonths,
  orgStructure: state.orgStructure,
}))
export default class PriceManage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      emptyMsg: '',
      code: '',
      headerHeight: [],
      attributesCheckeds: ['金额', '面积', '套数', '均价'],
      attributesCheckeds1: ['供货计划', '供货实际', '供货达成率'],
      subtractHeight: '165px',
    };
  }

  componentWillMount() {
    this.setState({
      headerHeight: [30, 30, 30, 60],
    });
  }

  componentDidMount() {
    const { match } = this.props;
    const params = {
      projectId: match.params.project,
    };
    this.fetchOverAllYears(params, match.params.project);
  }

  componentWillReceiveProps(nextProps) {
    // match变动
    if (
      this.props.match.params.project !== nextProps.match.params.project &&
      nextProps.match.params.project
    ) {
      const params = {
        projectId: nextProps.match.params.project,
      };
      const { dispatch } = this.props;
      dispatch({
        type: 'SupplyPlanDetailItems/clear',
      });
      this.fetchOverAllYears(params, nextProps.match.params.project);
    }
  }

  onChangeAttributesCheckeds(checkedValues) {
    this.setState({
      attributesCheckeds: checkedValues,
    });
  }

  getItems = (props, project, values = '') => {
    this.setState({ emptyMsg: '全盘供货计划数据加载中' });
    const self = this;
    const { dispatch } = props;
    const params = {
      projectId: project,
      code: values,
      type: '',
    };
    dispatch({
      type: 'SupplyPlanDetailItems/init',
      payload: {
        params,
      },
      callback: data => {
        if (_.isEmpty(data) && _.isEmpty(data.length)) {
          self.setState({ emptyMsg: '暂无全盘供货计划数据' });
        }
      },
    });
  };

  setCode(code) {
    this.setState({
      code,
    });
  }

  // 根据高级筛选按钮显示隐藏判断表格的高度
  subtractHeight = expandForm => {
    this.setState({
      subtractHeight: expandForm ? '225px' : '165px',
    });
  };

  fetchOverAllYears(params, project) {
    const { dispatch } = this.props;
    dispatch({
      type: 'SupplyPlanDetailItemsYears/fetch',
      payload: { params },
      callback: () => {
        this.getItems(this.props, project);
      },
    });
  }

  changeCurrentYear(data) {
    const { match, dispatch } = this.props;
    const self = this;
    dispatch({
      type: 'SupplyPlanDetailItemsYears/changeCurrentYear',
      payload: {
        currentYear: data.target.value,
      },
      callback: () => {
        self.getItems(this.props, match.params.project);
      },
    });
  }

  yearsRender() {
    let node;
    const { overAllYears, currentYear } = this.props;
    if (overAllYears.length) {
      node = (
        <div style={{ position: 'fixed', right: '40px' }}>
          <Radio.Group
            onChange={e => this.changeCurrentYear(e)}
            defaultValue={currentYear}
            buttonStyle="solid"
            size="small"
          >
            {overAllYears.map((element, index) => {
              if (index <= 15) {
                return (
                  <Radio.Button key={element} value={element}>
                    {element}
                  </Radio.Button>
                );
              }
            })}
            {overAllYears.length > 15 && <Radio.Button disabled>...</Radio.Button>}
          </Radio.Group>
        </div>
      );
    }
    return node;
  }

  overAllValueExport() {
    const { match } = this.props;
    const { code } = this.state;
    const params = {
      code,
      projectId: match.params.project,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(`${process.env.apiUrl}/api/v1/supplyPlan/overAllValueExport?${exportQueryString}`);
  }

  render() {
    const {
      attributesCheckeds,
      attributesCheckeds1,
      emptyMsg,
      headerHeight,
      subtractHeight,
    } = this.state;
    const treeData = this.props.items.searched;
    const { expandedRowKeys, searchItems } = this.props.items;
    const { overAllYears, currentYear, currentMonths } = this.props;
    let titleTree = [];
    let fixedColumns = [];
    if (currentYear && overAllYears.length) {
      titleTree = getTitleTree(attributesCheckeds, currentYear, currentMonths);
      fixedColumns = getFixedColumns(attributesCheckeds, currentYear, currentMonths);
    }
    const headerRenderer = utils.getHeaderRenderer(titleTree, 3, e => this.yearsRender(e));
    return (
      <PageHeaderWrapper
        className="page-header"
        breadcrumb={null}
        title={<ProjectsPath menu="SupplyPlan" {...this.props} />}
        tags={<CurrentStage {...this.props} />}
        extra={
          treeData.length > 0
            ? [
                <div key="1" className="header-btns">
                  <AuthorizedButton authority="supply_overall_versionComparison">
                    <Button
                      onClick={() => {
                        const orgTree = this.props.orgStructure.data;
                        const projectId = this.props.match.params.project;
                        const projectName = _.filter(orgTree, x => x.orgdepid === projectId)[0];
                        if (projectId && projectName) {
                          router.push({
                            pathname: '/common/supplyContrast',
                            query: {
                              projectName: escape(projectName.orgname),
                              projectId,
                            },
                          });
                        }
                      }}
                      style={{ marginRight: '5px' }}
                    >
                      版本对比
                    </Button>
                  </AuthorizedButton>
                  <AuthorizedButton authority="supply_overall_exportReport">
                    <Button onClick={() => this.overAllValueExport()} className="yellow-button">
                      导出报表
                    </Button>
                  </AuthorizedButton>
                </div>,
              ]
            : []
        }
      >
        <Card className="page-header-card">
          <div className={styles.container}>
            {!_.isEmpty(searchItems) ? (
              <PageTop
                getItems={this.getItems}
                setCode={e => this.setCode(e)}
                attributesCheckeds={attributesCheckeds}
                attributesCheckeds1={attributesCheckeds1}
                onChangeAttributesCheckeds={e => this.onChangeAttributesCheckeds(e)}
                {...this.props}
                expandForm={this.subtractHeight}
              />
            ) : null}
            {treeData.length > 0 && overAllYears.length ? (
              <Fragment>
                <BaseTable
                  subtractHeight={subtractHeight}
                  defaultExpandedRowKeys={expandedRowKeys}
                  expandColumnKey="name"
                  fixedColumns={fixedColumns}
                  headerHeight={headerHeight}
                  headerRenderer={headerRenderer}
                  treeData={treeData}
                />
              </Fragment>
            ) : (
              <PageEmpty emptyTitle={emptyMsg} />
            )}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
